/*******************************************************************************
版权声明: Copyright(C) HT-Tech Co., Ltd. 2020-2021. All rights reserved.
文件名称: htthr.c
文件描述: 线程操作接口定义
创 建 者: 陈位仅
创建时间: 2024年11月13日
修改历史:
1. 2024年11月13日    陈位仅      创建文件 
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "htmacro.h"
#include "htthr.h"

//线程执行函数
static void *routine(void *arg)
{
    struct htthr *pThr = (struct htthr *)arg;

    pthread_mutex_init(&pThr->mutex, NULL);
    pthread_cond_init(&pThr->cont, NULL);

    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

    do {
        pthread_mutex_lock(&pThr->mutex);
        if (pThr->bthrsusend) {
            if (0 != pthread_cond_wait(&pThr->cont, &pThr->mutex)) {
                perror("work:pthread_cond_wait");
                exit(-1);
            }
        }
        pthread_mutex_unlock(&pThr->mutex);

        pThr->run(pThr->arg);
    } while (pThr->bthrun);

    pthread_cond_destroy(&pThr->cont);
    pthread_mutex_destroy(&pThr->mutex);

    pThr->status = FALSE;
    pThr->run = NULL;

    return (void *)0;
}

//启动线程
int thr_start(struct htthr *pThr)
{
    if (NULL != pThr->run) {
        pThr->status = TRUE;
        if (0 == pthread_create(&pThr->tid, NULL, routine, (void *)pThr)) {
            return 0;
        }
    }
    
    pThr->status = FALSE;
    return -1;
}

//等待线程结束
int thr_wait(struct htthr *pThr)
{
    if (NULL != pThr->run) {
        return pthread_join(pThr->tid, NULL);
    }

    return -1;
}

//结束线程
int thr_cancel(struct htthr *pThr)
{
    if (NULL != pThr->run) {
        pthread_cancel(pThr->tid);

        pthread_cond_destroy(&pThr->cont);
        pthread_mutex_destroy(&pThr->mutex);

        return 0;
    }

    return -1;
}

//退出线程
void thr_exit(struct htthr *pThr)
{
    if (NULL != pThr->run) {
        pthread_mutex_lock(&pThr->mutex);
        pThr->bthrun = FALSE;
        pthread_mutex_unlock(&pThr->mutex);
    }
}

//线程等待信号创建
void thr_suspend(struct htthr *pThr)
{
    pthread_mutex_lock(&pThr->mutex);

    if (!pThr->bthrsusend) {
        pThr->bthrsusend = TRUE;
    }

    pthread_mutex_unlock(&pThr->mutex);
}

//触发线程等待信号
void thr_resume(struct htthr *pThr)
{
    pthread_mutex_lock(&pThr->mutex);
    if (pThr->bthrsusend) {
        pThr->bthrsusend = FALSE;
        pthread_cond_signal(&pThr->cont);
    }
    pthread_mutex_unlock(&pThr->mutex);
}
